<?php
namespace app\common\service;

use app\common\model\User;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class UserService
{
    /**
     * 填写邀请码
     * @param $code
     * @param $myId
     *
     * @throws DataNotFoundException
     * @throws PDOException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public function applyInvitationCode($code, $myId)
    {
        $myLeader = Db::name('user')
            ->field(['id', 'first_leader', 'second_leader', 'ancestor_relation'])
            ->where(['distribution_code' => $code])
            ->find();

        if (!$myLeader) {
            throw new \RuntimeException('无效的邀请码');
        }

        $myLeaderId = $myLeader['id'];
        $ancestorRelation = trim("{$myLeaderId},{$myLeader['ancestor_relation']}", ',');

        Db::name('user')->where(['id' => $myId])->update([
            'first_leader' => $myLeaderId,
            'second_leader' => $myLeader['first_leader'],
            'ancestor_relation' => $ancestorRelation,
        ]);

        // 更新我向下一级的第二上级
        Db::name('user')
            ->where(['first_leader' => $myId])
            ->update(['second_leader' => $myLeaderId]);

        // 更新与我相关的所有关系链
        $user = User::findOrEmpty($myId);
        $oldRelation = $user->ancestor_relation ? $user->id . ',' . $user->ancestor_relation : $user->id;
        $newRelation = trim("{$myId},{$ancestorRelation}", ',');

        Db::name('user')
            ->where("find_in_set({$myId},ancestor_relation)")
            ->exp('ancestor_relation', "replace(ancestor_relation, '{$oldRelation}', '{$newRelation}')")
            ->update();
    }


}